package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher apm = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转成HttpServletRequest类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("截取到的路径：{}" + request.getRequestURI());
        //1.获取请求路径
        String uri1 = request.getRequestURI();
        log.info("拦截的请求：{}",uri1);
        //3.得到结果，决定放行
        boolean check = check(uri1);
        //4.true，直接放行
        if (check){
            log.info("本次请求直接放行：{}",uri1);
            filterChain.doFilter(request, response);
            return;
        }
        //获取存入session中的id值
        Long id = (Long) request.getSession().getAttribute("employee");
        //5.false,判断是否登录过
        if ( id != null){
            //登录放行,获取登录id，存入本地线程容器中
            log.info("用户已登录，id：{}",request.getSession().getAttribute("employee"));
            UserHolder.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }
        //放行手机登录id
        Long loginPhoneId = (Long) request.getSession().getAttribute("loginPhoneId");
        if ( loginPhoneId != null){
            //登录放行,获取登录id，存入本地线程容器中
            log.info("用户已登录，id：{}",request.getSession().getAttribute("loginPhoneId"));
            UserHolder.setCurrentId(loginPhoneId);
            filterChain.doFilter(request, response);
            return;
        }
        //没登录过，响应数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    //2.匹配路径
    public boolean check(String uri1) {
        //直接放行的路径和静态资源
        String[] uri2 = new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        for (String s : uri2) {
            boolean match = apm.match(s, uri1);
            if (match){
                return true;
            }
        }
        return false;
    }
}
